<!-- Dom模板 -->
<template>
  <div class="login">
    <div class="logou">
      <img src="../img/06.png" alt="" />
      <h3>人人惠购</h3>
    </div>
    <div class="main">
      <van-cell-group>
        <van-field
          v-model="phone"
          required
          clearable
          label="手机号："
          maxlength="20"
          :error-message="phoneerr"
          @input="inpChange"
          ref="input"
        />
        <van-field
          v-model="password"
          required
          type="password"
          label="密码："
          maxlength="20"
          :error-message="passworderr"
          @input="paswordChange"
          ref="input"
        />
      </van-cell-group>
    </div>
    <div class="addre">
      <p @click="addAccount('01')">注册账号</p>
      <p @click="addAccount('02')">忘记密码？</p>
    </div>
    <div class="log">
      <van-button type="primary" ref="login" block @click="logins"
        >登录</van-button
      >
    </div>
  </div>
</template>
<script>
import * as API from "../api/login";
import { validation } from "../encapsulation";
import Storage from "../encapsulation/Storage";
import webSocket from "../utlis/webSocket";
export default {
  data() {
    return {
      msg: "测试",
      phone: "",
      phoneerr: "",
      password: "",
      passworderr: "",
      Forgots: "0"
    };
  },

  // 监听属性
  computed: {},
  // 组件挂载的地方
  components: {},
  // 生命周期 - 创建完成（访问当前this实例）
  created() {
    if (this.$route.query.path) {
      console.log("有路径");
      Storage.set("path", this.$route.query.path);
    }
  },

  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    console.log(this.$route);
    let tha = this;
    // 获取键盘码事件
    window.onkeydown = function(e) {
      // 回车
      if (e.keyCode == 13) {
        console.log("回车键");
        tha.logins();
      }
    };
  },
  // Vue方法定义
  methods: {
    // 注册账号和找回密码
    addAccount(type) {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 500,
        onClose: () => {
          this.$router.push({
            path: "/addAccount",
            query: {
              path: this.$route.path,
              type
            }
          });
        }
      });
    },
    //  点击登录提示
    logins() {
      console.log("点击了一下");
      // 正则验证
      let isphone = validation.isphone(this.phone);
      console.log(isphone);
      // 如果没有输入密码

      if (!this.phone && !isphone) {
        this.phoneerr = "请输入正确的手机号哦";
      }
      console.log(this.password);
      if (!this.password) {
        this.passworderr = "请输入密码";
      }
      console.log(this.phone, isphone);
      if (this.phone && isphone && this.password) {
        console.log("点击登录成功");
        this.$toast.loading({
          message: "加载中...",
          forbidClick: true,
          loadingType: "spinner",
          // 登录提示结束后提示登录状态
          onClose: async () => {
            console.log("开始发送请求");
            // 发送登录请求
            let res = await API.login({
              phone: this.phone,
              password: this.password,
              // type：01 代表点击的是登录
              type: "01"
            });
            console.log(res);
            // 判断登录状态
            if (res.code === "01") {
              // 提示登录状态
              this.$toast({
                message: "登录成功",
                position: "bottom"
              });
              // 01 :登陆成功
              // 直接跳到之前页面(从哪跳到login页的再跳到那个页面)
              // 并且把 返回来的用户数据存到localStorage里边
              Storage.set("token", res.data);
              this.$router.push({ path: Storage.get("path") });
              // 点击登录的时候保存当前账号
              webSocket.send(
                JSON.stringify({
                  // type值如果为login 表示需要等路由就保存当前账户
                  type: "login",
                  // 发送者的名字
                  uid: res.data.uid,
                  phone: res.data.phone,
                  img: res.data.img
                    ? res.data.img
                    : "https://cdn.jsdelivr.net/gh/zmf-6/cdn//img/portraits.png"
                })
              );
            } else if (res.code === "02") {
              // 提示登录状态
              this.phoneerr = res.msg;
            } else if (res.code === "03") {
              this.passworderr = res.msg;
            }
          }
        });
      }
    },
    // 输入框监听事件
    inpChange() {
      // 正则验证
      let isphone = validation.isphone(this.phone);
      console.log(isphone);
      if (!isphone) {
        //   如果手机号格式错误
        this.phoneerr = "请输入正确的手机号哦";
      } else {
        //   如果正确取消提示
        this.phoneerr = "";
      }
      if (!this.phone) {
        //   如果输入框为空了就取消提示
        this.phoneerr = "";
      }
    },
    // 监听密码输入框
    paswordChange() {
      // 只要改变密码输入框里的值就取消提示
      this.passworderr = "";
    }
  }
};
</script>

<style scoped>
/* @import url(''); 引入css类 */
.login {
  width: 100%;
  height: 100%;
  background: #fff;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
}
.logou {
  width: 80%;
  height: 200px;
  margin: 20px auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.logou img {
  margin-bottom: 10px;
  width: 100px;
}
.main {
  width: 80%;
  height: 100px;
  margin-top: 20px;
  margin: 0 auto;
}
.addre {
  width: 80%;
  height: 30px;
  display: flex;
  justify-content: space-between;
  margin: 40px auto;
  font-size: 12px;
  color: #3691ff;
}
.log {
  width: 80%;
  margin: 0 auto;
}
</style>
